package com.lgCore.client.workHandler;

import com.lgCore.netty.message.ReplyMsg;
import com.lgCore.netty.message.ReplyServerBody;
import com.lgCore.util.ExceptionUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 队列接受结果信息，保证数据同步
 */
public class ClientResultQueue {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClientResultQueue.class);
    //存放接口结果
    protected static ConcurrentHashMap<String, LinkedBlockingQueue<Object>> clientResultMap =
            new ConcurrentHashMap<String, LinkedBlockingQueue<Object>>();

    /**
     * 初始化结果队列，用于存放数据
     * @param businessId
     * @param queue
     * @throws Exception
     */
    public static void putResponse(String businessId, LinkedBlockingQueue<Object> queue)
            throws Exception {
        clientResultMap.put(businessId, queue);
    }

    /**
     * 删除
     * @param businessId
     */
    public static void removeResponse(String businessId) {
        // TODO Auto-generated method stub
        clientResultMap.remove(businessId);
    }

    /**
     * 队列填充结果信息
     * @param replyMsg
     * @throws Exception
     */
    public static void receiveResponse(ReplyMsg replyMsg) throws Exception {
        try {

            if(clientResultMap!=null && clientResultMap.containsKey(replyMsg.getBusinessId())){

                LinkedBlockingQueue<Object> queue = clientResultMap.get(replyMsg.getBusinessId());
                if (queue != null && replyMsg.isSuccese()==true) {
                    ReplyServerBody replyServerBody = (ReplyServerBody) replyMsg.getBody();
                    queue.put(replyServerBody);
                } else {
                    LOGGER.warn("give up the response,request id is:"
                            + replyMsg.getBusinessId() + ",because queue is null");
                }
            }else{
                LOGGER.error("give up the response,businessId id is:" + replyMsg.getBusinessId() + ",maybe because timeout!");
                return;
            }

        } catch (InterruptedException e) {

            LOGGER.info("put response error,request id is:" +  ExceptionUtil.ExceptionDetailAll(e));

            LOGGER.error("put response error,request id is:" + replyMsg.getBusinessId(), e);
            e.printStackTrace();
        }


    }
}

